package com.ruoyi.coin.utils;

import com.ruoyi.coin.enums.BuyEnum;
import com.ruoyi.coin.enums.OklinkChainEnum;
import com.ruoyi.coin.utils.okx.OkxUtil;
import com.ruoyi.common.config.CoinConfig;
import com.ruoyi.common.exception.ServiceException;

public class BuySellUtils {



    /**
     * 购买代币
     * @return
     */
    public static String buyToken(OklinkChainEnum oklinkChainEnum, String tokenAddress,int decimal){
        if(CoinConfig.getDebug()){
            return "123456789";
        }
        boolean priceFlag =getBnb2TokenPrice(oklinkChainEnum,BuyEnum.BUY,tokenAddress,decimal);

        if(!priceFlag){
            throw new ServiceException("池子为空");
        }

        String hash = OkxUtil.swap(oklinkChainEnum,BuyEnum.BUY, tokenAddress,decimal);
        return hash;
    }

    /**
     * 出售代币
     * @return
     */
    public static String sellToken(OklinkChainEnum oklinkChainEnum,String tokenAddress,int decimal){
        if(CoinConfig.getDebug()){
            return "123456789";
        }
        boolean priceFlag =getBnb2TokenPrice(oklinkChainEnum,BuyEnum.SELL,tokenAddress,decimal);

        if(!priceFlag){
            throw new ServiceException("池子为空");
        }

        //进行授权
        boolean approveFlag = OkxUtil.approveToken(oklinkChainEnum, tokenAddress);
        if(!approveFlag){
            throw new ServiceException("授权失败");
        }

        String hash = OkxUtil.swap(oklinkChainEnum,BuyEnum.SELL, tokenAddress,decimal);
        return hash;
    }

    //获取价格
    private static boolean getBnb2TokenPrice(OklinkChainEnum oklinkChainEnum,BuyEnum buyEnum,String tokenAddress,int decimal){
        boolean priceFlag =false;
        for (int i = 0; i < 3; i++) {
            priceFlag = OkxUtil.getBnb2TokenPrice(oklinkChainEnum,buyEnum, tokenAddress, decimal);
            if(priceFlag){
                break;
            }else{
                try{
                    Thread.sleep(5000);
                }catch (Exception e){
                    e.printStackTrace();
                }
            }

        }
        return priceFlag;
    }
}
